export default {
  // 为当前模块开启命名空间
  namespaced: true,

  // 模块的 state 数据
  state: () => ({
    cart:uni.getStorageSync('cart') || []
  }),

  // 模块的 mutations 方法
  mutations: {
    savaTostate(state) {
        uni.setStorageSync('cart',state.cart)
    },
    addToCart(state, goods) {
      let f = state.cart.find(t => t.goods_id === goods.goods_id) 
      if(f) {
        f.goods_count++
      } else {
        state.cart.push(goods)
      }
      this.commit('my-cart/savaTostate')
    },
    upDataChangeRadio(state,payload){
    let f = state.cart.find(t=> t.goods_id === payload.goods_id)
    if(f) {
     f.goods_state = payload.goods_state
     this.commit('my-cart/savaTostate')
    }
    },
    // 更改商品数量
    upDataChangeCount(state,payload){
    let f = state.cart.find(t=> t.goods_id === payload.goods_id)
    if(f) {
     f.goods_count = payload.goods_count
     this.commit('my-cart/savaTostate')
    }
    },
    deleteGoods(state,paylod) {
    let index =  state.cart.findIndex(t => t.goods_id === paylod.goods_id)
    if(index !== -1) {
      state.cart.splice(index, 1)
      this.commit('my-cart/savaTostate')
    }
    },
    //实现购物车的全选反选
    updataAllGoodsCheckoued(state,newState){
      // 遍历每一项的商品选中属性, 并为其赋值
      state.cart.forEach(t => t.goods_state = newState)
      this.commit('my-cart/savaTostate')
    }
  },
  // 模块的 getters 属性
  getters: {
    // 商品总数
    total(state) {
      let results = 0
      state.cart.forEach(i => results+=i.goods_count)
      return results
    },
    // 选中的商品数量
    checkoutCount(state) {
      return state.cart.filter(t => t.goods_state).reduce((sum,m)=> sum+ m.goods_count,0)
    },
    // 实现计算商品总价
    checkoutCountAmount(state) {
      return state.cart.filter(t=>t.goods_state).reduce((sum,m)=>sum+m.goods_count * m.goods_price,0).toFixed(2)
    }
  },
}
